package com.shen.JUC.fockjoin;

import java.util.concurrent.RecursiveTask;

//求和
/*forkJoin使用方法
* 1.forkJoinPool 通过它执行
* 2.计算任务 forkJoinPool.execute(ForkJoinTask task)
* */
public class Add extends RecursiveTask<Long> {

    private Long start;
    private Long end;
    private Long door=10000L;//临界值

    public Add(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
       if ((end-start)<door){
           Long sum=0L;
           for (Long i = start; i <end ; i++) {
               sum +=i;
           }
          return sum;
       }else{//forkjoin
           long mid = (start + end) / 2;
           Add add1 = new Add(start, mid);
           add1.fork();//拆分任务，把任务压入线程队列
           Add add2 = new Add(mid+1, end);
           add2.fork();
           return add1.join() + add2.join();
       }

    }
}
